<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="出库单号" prop="shipmentOrderNo">
          <el-input v-model="queryParams.shipmentOrderNo" placeholder="请输入出库单号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="出库类型" prop="shipmentOrderType">
          <el-radio-group v-model="queryParams.shipmentOrderType" @change="handleQuery">
            <el-radio-button label="">
              全部
            </el-radio-button>
            <el-radio-button v-for="dict in shipment_order_type" :label="dict.value">
              {{ dict.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出库订单" prop="orderNo">
          <el-input v-model="queryParams.orderNo" placeholder="请输入出库订单" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="出库状态" prop="shipmentOrderStatus">
          <el-radio-group v-model="queryParams.shipmentOrderStatus" @change="handleQuery">
            <el-radio-button label="">
              全部
            </el-radio-button>
            <el-radio-button v-for="dict in shipment_order_status" :label="dict.value">
              {{ dict.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <router-link to="/wms/orderdetail/index">
            <el-button type="primary" plain icon="Plus" v-hasPermi="['wms:order:add']">创建出库单</el-button>
          </router-link>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>


    <el-card style="margin-top: 15px;">
      <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column type="expand">
          <template #default="props">
            <div>
              <b style="font-size: larger;">物料明细</b>
              <el-button type="primary" style="margin-left: 800px;margin-bottom: 10px;" icon="Van"
                v-if="props.row.shipmentOrderStatus !== 3 && !props.row.delivery"
                @click="Delivery(props.row, 3)">发货</el-button>
              <el-button type="primary" style="margin-left: 800px;margin-bottom: 10px;"
                @click="openDelivery(props.row.shipmentOrderNo)" v-if="props.row.delivery">
                创建物流单号
              </el-button>
              <el-button type="primary" style="margin-left: 16px;margin-bottom: 10px;"
                @click="openDrawer(props.row.shipmentOrderNo)" v-if="!props.row.delivery">
                物流信息
              </el-button>
              <el-table :data="props.row.details">
                <el-table-column label="物料名称" prop="item_name" />
                <el-table-column label="物料编号" prop="item_no" />
                <el-table-column label="出库数量" prop="plan_quantity" />
                <el-table-column label="总价格" prop="money" />
                <el-table-column label="出库状态" align="center">
                  <template #default="scope">
                    <dict-tag :options="shipment_order_status" :value="scope.row.shipment_order_status" />
                  </template>
                </el-table-column>
                <el-table-column label="出库仓" prop="warehouse_name" />
                <el-table-column label="出库库区" prop="area_name" />
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-button link type="primary" icon="Van"
                      v-if="scope.row.shipment_order_status === 1 && !props.row.delivery"
                      @click="Delivery(scope.row, 3, props.row.shipmentOrderNo)">发货</el-button>
                    <el-button link type="danger" icon="FolderDelete"
                      v-if="scope.row.shipment_order_status === 1 && !props.row.delivery"
                      @click="Delivery(scope.row, props.row.shipmentOrderNo)">作废</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="出库单号" align="center" prop="shipmentOrderNo" />
        <el-table-column label="出库类型" align="center" prop="shipmentOrderType">
          <template #default="scope">
            <dict-tag :options="shipment_order_type" :value="scope.row.shipmentOrderType" />
          </template>
        </el-table-column>
        <el-table-column label="订单号" align="center" prop="orderNo" />
        <el-table-column label="客户" align="center" prop="customerName" />
        <el-table-column label="出库状态" align="center" prop="shipmentOrderStatus">
          <template #default="scope">
            <dict-tag :options="shipment_order_status" :value="scope.row.shipmentOrderStatus" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-if="scope.row.shipmentOrderStatus === 1 || scope.row.shipmentOrderStatus === 2">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['wms:order:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 发货出库单对话框 -->
    <el-dialog title="创建发货单" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="出库单" prop="shipmentOrderId">
          <el-input v-model="form.shipmentOrderId" placeholder="请输入编号" clearable disabled />
        </el-form-item>
        <el-form-item label="承运商" prop="carrierId">
          <el-select v-model="form.carrierId" placeholder="请选择承运商">
            <el-option v-for="dict in Carrier" :key="'key-' + dict.carrierNo" :label="dict.carrierName"
              :value="dict.carrierNo" />
          </el-select>
        </el-form-item>
        <el-form-item label="发货时间" prop="deliveryDate">
          <el-date-picker clearable :disabled-date="disabledPastDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择发货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="快递单号" prop="trackingNo">
          <el-input v-model="form.trackingNo" placeholder="请输入快递单号" clearable />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.deliveryRemark" placeholder="请输入备注" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 抽屉显示物流信息  -->
    <el-drawer v-model="drawer" title="物流信息">
      <h3>出库单号</h3>
      <h3>&emsp;&emsp;{{ delivery.shipmentOrderId }}</h3>
      <h3>承运商</h3>
      <h3>&emsp;&emsp;{{ delivery.carrierName }}</h3>
      <h3>快递单号</h3>
      <h3>&emsp;&emsp;<a :href="'https://www.kuaidi100.com/all/hhair56.shtml?mscomnu=' + delivery.trackingNo"
          style="color: skyblue;">{{ delivery.trackingNo }}</a></h3>
      <h3>发货日期</h3>
      <h3>&emsp;&emsp;{{ delivery.deliveryDate }}</h3>
    </el-drawer>
  </div>
</template>

<script setup name="Orders">
import { listOrder, getOrder, delOrder, addOrder, updateOrder, ByShipmentOrderNo } from "@/api/wms/orders";
import { listCarrier } from "@/api/wms/carrier";
import { addDelivery, getShipmentOrderId } from "@/api/wms/delivery";
import { ordersList, updateDetail } from "@/api/wms/orderdetail"

const { proxy } = getCurrentInstance();
const { shipment_order_type, shipment_order_status } = proxy.useDict('shipment_order_type', 'shipment_order_status');
// 禁用今天之前的日期
function disabledPastDate(time) {
  return time.getTime() < Date.now() - 8.64e7; // 8.64e7 毫秒数代表一天
}
const orderList = ref([]);
const Carrier = ref();//承运商数据
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
//控制抽屉的显示
const drawer = ref(false)
//发货记录的数据
const delivery = ref();

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shipmentOrderNo: null,
    shipmentOrderType: "",
    orderNo: null,
    customerId: null,
    receivableAmount: null,
    shipmentOrderStatus: "",
    checkStatus: null,
    checkUserId: null,
    checkTime: null,
    customerName: null,
  },
  rules: {
    carrierId: [
      { required: true, message: "承运商不能为空", trigger: "change" }
    ],
    trackingNo: [
      { required: true, message: "快递单号不能为空", trigger: "blur" }
    ],
    deliveryDate: [
      { required: true, message: "发货时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询出库单列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    console.log(response.rows);
    
    orderList.value = response.rows;
    orderList.value.forEach(item => {
      ordersList({ shipmentOrderId: item.shipmentOrderNo.replaceAll("-", "").slice(2) }).then(response => {
        item.details = response.rows;
      })
      getShipmentOrderId(item.shipmentOrderNo.replaceAll("-", "").slice(2)).then(response => {
        if (response.data === undefined) {
          item.delivery = true;
        } else {
          item.delivery = false;
        }
      })
    })
    total.value = response.total;
    loading.value = false;
  });
}

listCarrier().then(response => {
  Carrier.value = response.rows;
})

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  // console.log(queryParams.value)
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加出库单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  proxy.$router.push({ path: "/wms/orderdetail/index", query: { shipmentOrderNo: row.shipmentOrderNo } })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      addDelivery(form.value).then(response => {
        proxy.$modal.msgSuccess("物流添加成功");
        cancel();
        getList();
      })
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.shipmentOrderNo
  proxy.$modal.confirm('确认删除出库单【' + row.shipmentOrderNo + '】吗？').then(function () {
    loading.value = true;
    delOrder(id).then(() => {
      proxy.$modal.msgSuccess("删除成功");
    }).finally(() => {
      loading.value = false;
      getList();
    });
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wms/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

//打开发货弹框
function openDelivery(shipmentOrderNo) {
  reset();
  // console.log(row);
  form.value.shipmentOrderId = shipmentOrderNo.replaceAll("-", "").slice(2);
  console.log(form.value);
  open.value = true;
}

//打开抽屉
function openDrawer(shipmentOrderNo) {
  getShipmentOrderId(shipmentOrderNo.replaceAll("-", "").slice(2)).then(response => {
    console.log(response.data)
    delivery.value = response.data;
    drawer.value = true;
  })
}


//发货和作废按钮
function Delivery(row, state, shipmentOrderNo) {
  let params = {};
  if (state === 3) {
    if (shipmentOrderNo === undefined) {
      // params = Object.assign(params, row);
      params = JSON.parse(JSON.stringify(row))
      params.shipmentOrderStatus = state;
      params.details.forEach(item => {
        item.itemId = item.item_no;
        item.shipmentOrderStatus = item.shipment_order_status;
        item.planQuantity = item.plan_quantity;
        item.warehouseId = item.warehouse_id;
        item.areaId = item.area_id;
        item.itemName = item.item_name;
      });
      proxy.$modal.confirm('你确定要全部发货吗？').then(() => {
        // console.log(params)
        ByShipmentOrderNo(params).then(response => {
          // console.log(response)
          proxy.$modal.msgSuccess("全部发货成功");
          getList();
        })
      }).catch(() => { });
    } else {
      params = JSON.parse(JSON.stringify(row));
      params.itemId = row.item_no;
      params.planQuantity = row.plan_quantity;
      params.warehouseId = row.warehouse_id;
      params.areaId = row.area_id;
      params.itemName = row.item_name;
      params.shipmentOrderStatus = state;
      params.shipmentOrderNo = shipmentOrderNo;
      // console.log(params);
      proxy.$modal.confirm('你确定将' + params.itemName + '发货吗？').then(() => {
        updateDetail(params).then(response => {
          proxy.$modal.msgSuccess(params.itemName + "发货成功");
          getList();
        })
      }).catch(() => { });
    }
  } else {
    params = JSON.parse(JSON.stringify(row));
    params.itemId = row.item_no;
    params.planQuantity = row.plan_quantity;
    params.warehouseId = row.warehouse_id;
    params.areaId = row.area_id;
    params.itemName = row.item_name;
    params.shipmentOrderStatus = state;
    params.shipmentOrderNo = shipmentOrderNo;
    // console.log(params);
    proxy.$modal.confirm('你确定将' + params.itemName + '作废吗？').then(() => {
      updateDetail(params).then(response => {
        proxy.$modal.msgSuccess(params.itemName + "已作废");
        getList();
      })
    }).catch(() => { });
  }
}

getList();
</script>
